let BaseController = require('./BaseController')
let fs = require('fs')
let path = require('path')
class Controller extends BaseController {
    constructor() {
        super();
        this.baseSrc = `d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/09字典/沪深股票列表/`;

        this.encode = 'UTF-8'
        this.params = {
            pageIndex: 1,
            date: new Date().format('yyyy-MM-dd')
        }
        this.pageTotal = '';
        this.data = []

    }
    /**
     * 获取url
     */
    getUrl(date) {
        //http://quote.eastmoney.com/center/gridlist.html#hs_a_board
        return `http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?cb=jQuery112409772865367230104_1533263455968&type=CT&token=4f1862fc3b5e77c150a2b985b12db0fd&sty=FCOIATC&js=(%7Bdata%3A%5B(x)%5D%2CrecordsFiltered%3A(tot)%7D)&cmd=C._A&st=(ChangePercent)&sr=-1&p=${this.params.pageIndex}&ps=20&_=1533263455988`;
    }

    /**
     * 获取历史数据
     */
    async getHistory() {
        console.log('27字典_沪深股票列表Controller')
        if (this.pageTotal === '' || this.params.pageIndex <= this.pageTotal) {
            console.log(JSON.stringify(this.params))
            let result = await this.getData('', this.isCache)
            result = this.axiosDataFormat(result.toString());
            let pageDate = result.data;
            this.data.push(pageDate.join('\n') + '\n')
            this.params.pageIndex++;
            await this.getHistory()
        }
    }
    /**
     * 数据格式化
     */
    axiosDataFormat(data) {
        let result = null
        try {
            result = JSON.parse(data.replace('jQuery112409772865367230104_1533263455968(', '').replace(/\)$/, ''))
        } catch (err) {
            result = eval('(' + data.replace('jQuery112409772865367230104_1533263455968(', '').replace(/\)$/, '') + ')')
        }
        this.pageTotal = Math.ceil(result.recordsFiltered / 20)
        this.params.pageTotal = this.pageTotal;
        return result
    }

    /**
     * 写csv
     */
    writeCsv(arr) {
        if (!fs.existsSync(this.baseSrc)) {
            this.mkdirs(this.baseSrc)
        }
        if (arr && arr.length) {
            this.file = path.join(this.baseSrc, `沪深股票列表_${this.params.date.replace(/-/g, '')}.csv`)
            fs.writeFileSync(this.file, arr.join('\n'), 'UTF-8')
        }
    }

    async main(startDate = '2015-01-01', isCache = true) {
        this.isCache = isCache;
        console.log('--->27字典_沪深股票列表Controller')
        await this.getHistory()
        this.writeCsv(this.data);
    }
}

let controller = new Controller()
module.exports = controller
